package com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl;

import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.cucc.order.accept.chain.AbstractOrderHandler;
import com.iwhalecloud.bss.kite.cucc.order.cache.OrderRequestCache;
import com.iwhalecloud.bss.kite.cucc.order.event.BeforeOrderSaveEvent;
import com.iwhalecloud.bss.kite.cucc.order.util.RuleTriggerUtil;
import com.iwhalecloud.bss.kite.dataservice.entity.OrderItem;
import com.iwhalecloud.bss.kite.order.client.dto.OrderContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 订单受理流程：订单保存前处理
 */
@Component
public class OrderBeforeSaveHandler extends AbstractOrderHandler {

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void doHandle(OrderRequest orderRequest) {
        // 订单保存前事件埋点
        BeforeOrderSaveEvent beforeOrderSaveEvent = new BeforeOrderSaveEvent(this, orderRequest);
        applicationContext.publishEvent(beforeOrderSaveEvent);

        // 订单保存前规则埋点
        List<Map<String, Object>> orderInfoList = new ArrayList<>();
        List<OrderItem> orderItems = OrderContainer.ofRequest(orderRequest).listOrderItems();
        for (OrderItem orderItem : orderItems) {
            orderInfoList.add(KiteMapUtils.camelToUnderline(KiteMapUtils.beanToMap(orderItem)));
        }
        String custOrderId = orderRequest.getCustOrderId();
        String custId = orderRequest.getCustId();
        RuleTriggerUtil.bfOrderSaveRule(custOrderId, custId, orderInfoList, orderRequest);

        if (Objects.equals(Boolean.TRUE, orderRequest.getPreCheck())) {
            // 缓存OrderRequest后终止流程
            OrderRequestCache.put(orderRequest.getCustOrderId(), orderRequest);
            orderRequest.setAbort(true);
        }
    }
}
